var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    dataCheckList: [],
    showPage: false,
    time: '',
    name: '',
    desc: '',
    userName: ''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options:', options)
    var that = this
    that.setData({
      cardNumber: options.card,
      // userName: options.cardOwner ? options.cardOwner : '',
      // name: options.userName ? options.userName : '',
      // desc: options.memo ? options.memo : '',
    })
    let nophone = app.getUserLoginNoPhone();
    if (nophone == 1) {
      that.setData({
        btnState: true
      })
    } else {
      that.setData({
        btnState: false,
        phoneNumber: wx.getStorageSync('iphone')
      })
    }
    var arra = []
    that.data.dataCheckList.forEach((item, index) => {
      if (item.checked) {
        arra.push(item)
      }
    })
    that.setData({
      array: arra
    })
    that.getCardList()
  },
  getCardList() {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    // 卡列表
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/icardHospitaled/detail',
        header: header,
        data: {
          cardNum: that.data.cardNumber
        },
        success: (res) => {
          getApp().hideLoading()
          console.log(res, 'res')
          if (res.data.result == 0) {
            let cardInfo = res.data.data.cardInfo
            if(!cardInfo){
              cardInfo = {}
            }
            if (res.data.data.equipment.length > 0 || res.data.data.selectEquipment.length > 0) {
              that.setData({
                dataList: res.data.data.selectEquipment ? res.data.data.selectEquipment : '',
                dataCheckList: res.data.data.equipment ? res.data.data.equipment : '',
                address: cardInfo.address ? cardInfo.address : '',
                isUser: !res.data.data.isNursing,
                cardNumber: cardInfo.cardNumber ? cardInfo.cardNumber : '',
                nursingName: cardInfo.nursingName ? cardInfo.nursingName : '',
                nursingPhone: cardInfo.nursingPhone ? cardInfo.nursingPhone : '',
                qrcode: res.data.data.qrcode ? res.data.data.qrcode : '',
                showPage: true,
                userName: cardInfo.ownerPhone ? cardInfo.ownerPhone : '',
                name: cardInfo.ownerName ? cardInfo.ownerName : '',
                desc: cardInfo.memo ? cardInfo.memo : '',
                // userName: cardInfo.userName ? cardInfo.userName : '',
              })
            } else {
              wx.showModal({
                title: '温馨提示',
                content: '该卡尚未绑定！',
                showCancel: false,
                success(res) {
                  wx.reLaunch({
                    url: '../../../pages/index/index',
                  })
                }
              })
            }
          } else {
            that.setData({
              showdialog: true,
              title: res.data.description,
              jump: true
            })
            // setTimeout(()=>{
            //   wx.reLaunch({
            //     url: '../index/index',
            //   })
            // },4000)

          }


          console.log(that.data.dataList, that.data.dataCheckList)
        },
        fail: (err) => {
          that.setData({
            showdialog: true,
            title: '请求失败',
          })
        }
      })
    })
  },
  // 确定跳转 前往支付押金页面
  jumpPayDeposit() {
    var that = this
    that.updateUserCardShip()
    console.log(that.data.cardNumber, 'that.data.cardNumber')
    if (that.data.isUser) {
      wx.navigateTo({
        url: '../../../pages/payDeposit/payDeposit?ids=' + that.data.str + '&card=' + that.data.cardNumber,
      })
    } else {
      wx.navigateTo({
        url: '../../../pages/payDepositWorker/payDepositWorker?ids=' + that.data.str + '&card=' + that.data.cardNumber,
      })
    }
    wx.showLoading({
      title: '加载中',
    })


  },
  // 归属input框
  changeNumber(e) {
    clearTimeout(this.data.time)
    var time = setTimeout(() => {
      this.setData({
        userName: e.detail.value
      })
      console.log(this.data.userName)
    }, 1000)
    this.data.time = time
  },
  // 归属input框
  changeName(e) {
    clearTimeout(this.data.timer)
    var timer = setTimeout(() => {
      this.setData({
        name: e.detail.value
      })
      console.log(this.data.name)
    }, 1000)
    this.data.timer = timer
  },
  bindTextAreaBlur(e) {
    this.setData({
      desc: e.detail.value
    })
    console.log(this.data.desc)
  },
  // 多选框的触发事件
  checkboxChange(e) {
    var that = this
    var str = ''
    var arr = []
    str += e.detail.value
    e.detail.value.forEach((item, i) => {
      that.data.dataCheckList.forEach((value, j) => {
        if (that.data.dataCheckList[j].equTypeId == e.detail.value[i]) {
          arr.push(that.data.dataCheckList[j])
        }
      })
    })
    that.setData({
      array: arr, //选中设备的数组，用作路由跳转
      str: str, // 选中的设备传参的字符串
      select: e.detail.value // 选中的数组设备id
    })
    if (that.data.array.length) {
      that.setData({
        isdisabled: false
      })
    } else {
      that.setData({
        isdisabled: true
      })
    }
    console.log(str, that.data.array, that.data.array.length)
  },
  callPhone(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.hotline //仅为示例，并非真实的电话号码
    })
  },
  // 如果用过没有登录 让用户授权登录
  getPhoneNumber: function (e) {
    console.log(e, 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee')
    var that = this;
    if (e.detail.errMsg.indexOf('user deny') != -1) {
      return;
    } else {
      wx.showLoading({
        title: '登录中...',
      });
      //解密数据并登录成功
      app.executeRequest(function (header) {
        wx.request({
          url: app.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
          header: header,
          data: {
            iv: encodeURIComponent(e.detail.iv),
            encryptedData: encodeURIComponent(e.detail.encryptedData)
          },

          success: function (res) {
            getApp().hideLoading();
            console.log('getPhoneNumber--res', res);
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            if (res.data.result === 0) {
              //登录成功
              // that.setData({
              //   showdialog:true,
              //   title: '登录成功',
              // })
              var btt = that.data.phoneAuthBtt;
              wx.setStorageSync('nophone', '2');
              app.globalData.loginData.nophone = 2;
              wx.setStorageSync('iphone', res.data.phone)
              that.setData({
                user_id: res.data.uid ? res.data.uid : '',
                phoneAuthStatus: false,
                phoneAuthBtt: ''
              })
              that.jumpPayDeposit()

            } else if (res.data.result === 4) {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: res.data.description,
                success(res) {}
              })
            } else {
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'scan',
                loading_show: false
              });
              that.setData({
                showdialog: true,
                title: '请先登录',
              })
            }
          },
          fail: function (err) {
            getApp().hideLoading();
          }
        });

      });
    }
  },
  updateUserCardShip() {
    var that = this
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/hospitalized/updateUserCardShip',
        header: header,
        data: {
          cardNumber: that.data.cardNumber,
          userPhone: that.data.userName,
          userName: that.data.name,
          memo: that.data.desc
        },
        success: function (res) {
          getApp().hideLoading();
          console.log(res, '保存成功')

        },
        fail: function (err) {
          getApp().hideLoading();
        }
      });

    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.getCardList()
    let nophone = app.getUserLoginNoPhone();
    if (nophone == 1) {
      that.setData({
        btnState: true
      })
    } else {
      that.setData({
        btnState: false
      })
    }
    if (that.data.array.length) {
      that.setData({
        isdisabled: false
      })
    } else {
      that.setData({
        isdisabled: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})